const { Tag } = require('../../model');

const addTag = async (req, res) => {
  console.log('添加tags');
  // post 通过 req。body  获取传输过来的参数
  const { label, value, isDeleted = 0 } = req.body;
  console.log(req.body);
  try {
    const model = await Tag.findAll({
      where: {
        value,
      },
    }); //查询是否存在
    console.log(model);
    if (model.length) {
      res.send({ msg: '标签已存在', errcode: 1, success: false });
      return;
    }
    const tagCreate = await Tag.create({ label, value, isDeleted }); // 创建一条记录
    if (!tagCreate) {
      res.send({ errcode: 1, msg: '添加失败:', success: false });
      return;
    }
    res.send({
      errcode: 0,
      msg: 'ok',
      success: true,
    });
  } catch (error) {
    console.log('服务错误:', error);
    res.send({ errcode: 1, msg: '添加失败:' + error, success: false });
  }
};

const listTag = async (req, res) => {
  try {
    const tagList = await Tag.findAll();
    res.send({
      errcode: 0,
      msg: 'ok',
      success: true,
      data: tagList,
    });
  } catch (error) {
    console.log('服务错误:', error);
    res.send({ errcode: 1, msg: '查下失败:' + error, success: false });
  }
};

module.exports = {
  addTag,
  listTag,
};
